package backend.service;

import java.util.List;

import backend.dal.DALException;
import backend.dal.DAOFactory;
import backend.dal.UserDAO;
import backend.model.User;
import backend.util.ConnectionType;
import backend.util.PasswordEncrypter;

public class UserServiceImpl implements UserService {

	private DAOFactory df;
	private UserDAO userDAO;

	public UserServiceImpl(ConnectionType ct) {
		df = DAOFactory.getInstance(ct);
		userDAO = df.getUserDAO();
	}

	@Override
	public User getUserById(int id) throws ServiceException {
		try {
			return userDAO.getUserById(id);
		} catch (DALException e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

	@Override
	public void insertUser(User user) throws ServiceException {
		try {
			String encrPass = PasswordEncrypter.generateHashedPassword(user.getPassword(), "");
			user.setPassword(encrPass);
			userDAO.insertUser(user);
		} catch (DALException e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

	@Override
	public void updateUser(User user) throws ServiceException {
		try {
			userDAO.updateUser(user);
		} catch (DALException e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

	@Override
	public void deleteUser(Integer id) throws ServiceException {
		try {
			userDAO.deleteUser(id);
		} catch (DALException e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

	@Override
	public List<User> viewAllUsers() throws ServiceException {
		try {
			return userDAO.viewAllUsers();
		} catch (DALException e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

	@Override
	public String getUserPassword(Integer id) throws ServiceException {
		try {
			return userDAO.getUserPassword(id);
		} catch (DALException e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}

}
